<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" disabled placeholder="系统自动生成"></a-input>
            </a-form-model-item>
          </a-col>

          <a-col :span="8">
            <a-form-model-item label="年月" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="summaryMonth">
              <j-date
                :show-time="false"
                date-format="YYYY-MM"
                placeholder="请选择"
                mode="month"
                v-model="model.summaryMonth"
              ></j-date>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="营销订单汇总子表" :key="refKeys[0]" :forceRender="true">
        <a-row :gutter="10">
          <a-col :span="2">
            <a-button @click="handleAddOrders">添加订单</a-button>
          </a-col>
        </a-row>
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="tslTradeOrderSummaryDetailTable.loading"
          :columns="tslTradeOrderSummaryDetailTable.columns"
          :dataSource="tslTradeOrderSummaryDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
          :toolbarConfig="{ slot: ['prefix', 'suffix'], btn: ['remove', 'clearSelection'] }"
        />
      </a-tab-pane>
    </a-tabs>
    <select-wait-summary-trade-order-modal ref="selectModal" @orderOk="onOrderOk" />
  </a-spin>
</template>

<script>
import { getAction } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import { parseTime } from '@/utils/index.js'

import SelectWaitSummaryTradeOrderModal from './SelectWaitSummaryTradeOrderModal.vue'

export default {
  name: 'TslTradeOrderSummaryForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer,
    SelectWaitSummaryTradeOrderModal,
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: {
        code: '',
        summaryMonth: parseTime(new Date(), '{y}-{m}'),
      },
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        code: [{ required: false, message: '请输入单据编号!' }],
        summaryMonth: [
          { required: true, message: '请选择年月!' },
          {
            validator: (rule, value, callback) =>
              validateDuplicateValue('tsl_trade_order_summary', 'summary_month', value, this.model.id, callback),
          },
        ],
      },
      refKeys: ['tslTradeOrderSummaryDetail'],
      tableKeys: ['tslTradeOrderSummaryDetail'],
      activeKey: 'tslTradeOrderSummaryDetail',
      // 营销订单汇总子表
      tslTradeOrderSummaryDetailTable: {
        loading: false,
        dataSource: [],
        columns: [
          // {
          //   title: '主表ID',
          //   key: 'mainId',
          //    type: JVXETypes.input,
          //   width:"200px",
          //   placeholder: '请输入${title}',
          //   defaultValue:'',
          // },
          {
            title: '营销订单编号',
            key: 'orderCode',
            type: JVXETypes.normal,
            width: '150px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '订货数量',
            key: 'orderWeight',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            statistics: ['sum'],
            defaultValue: '',
          },
          {
            title: '单位',
            key: 'weightUnit',
            type: JVXETypes.select,
            disabled: true,
            width: '100px',
            dictCode: 'zl_unit',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '交货日期',
            key: 'deliveryDate',
            type: JVXETypes.normal,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '实际交货日期',
            key: 'actualDeliveryDate',
            type: JVXETypes.date,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '备注',
            key: 'remark',
            type: JVXETypes.input,
            width: '300px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
        ],
      },
      url: {
        add: '/sale/tslTradeOrderSummary/add',
        edit: '/sale/tslTradeOrderSummary/edit',
        queryById: '/sale/tslTradeOrderSummary/queryById',
        tradeOrderList: '/review/bussInternationalTradeOrders/listWaitSummary',
        tslTradeOrderSummaryDetail: {
          list: '/sale/tslTradeOrderSummary/queryTslTradeOrderSummaryDetailByMainId',
        },
      },
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {},
  methods: {
    handleAddOrders(){
      this.$refs.selectModal.add();
    },
    onOrderOk(rows) {
      console.log('选择营销订单：', rows)
      let d = new Date()
      let dStr = parseTime(d, '{y}-{m}-{d}')
      const codes = this.tslTradeOrderSummaryDetailTable.dataSource.map((item) => item.orderCode)
      const that = this
      if (rows && rows.length > 0) {
        rows.forEach((item) => {
          if (codes && codes.length > 0 && codes.indexOf(item.code) > -1) {
            console.log('选择重复订单！', item.code)
            return
          }
          let detail = {}
          detail.orderCode = item.code
          detail.orderWeight = item.weight
          detail.weightUnit = item.weightUnit
          detail.deliveryDate = item.deliveryDate
          detail.actualDeliveryDate = dStr
          detail.remark = item.reviewRemark
          that.tslTradeOrderSummaryDetailTable.dataSource.push(detail)
        })
      }
    },
    addBefore() {
      this.tslTradeOrderSummaryDetailTable.dataSource = []
    },
    addAfter() {
      let d = new Date()
      const that = this
      let dStr = parseTime(d, '{y}-{m}-{d}')
      getAction(this.url.tradeOrderList).then((res) => {
        console.log(res)
        if (res.success) {
          let orders = res.result
          if (orders && orders.length > 0) {
            orders.forEach((item) => {
              let detail = {}
              detail.orderCode = item.code
              detail.orderWeight = item.weight
              detail.weightUnit = item.weightUnit
              detail.deliveryDate = item.deliveryDate
              detail.actualDeliveryDate = dStr
              detail.remark = item.reviewRemark
              that.tslTradeOrderSummaryDetailTable.dataSource.push(detail)
            })
            console.log('获取待汇总的营销订单列表：', that.tslTradeOrderSummaryDetailTable.dataSource)
          }
        }
      })
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {})
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.tslTradeOrderSummaryDetail.list, params, this.tslTradeOrderSummaryDetailTable)
      }
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            resolve(allValues)
          })
          .catch((e) => {
            if (e.error === VALIDATE_FAILED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        tslTradeOrderSummaryDetailList: allValues.tablesValue[0].tableData,
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
  },
}
</script>

<style scoped></style>
